import torch
import dltools
from torch import nn
import matplotlib.pyplot as plt

n_train = 50
# torch.rand 返回[0,1)的随机数
x_train,_ = torch.sort(torch.rand(n_train) * 5)

def f(x):
    # 生成数据，也可以是其他公式
    return 2 * torch.sin(x) + x ** 0.8

y_train = f(x_train) + torch.normal(0.0, 0.5, (n_train,))
x_test = torch.arange(0, 5, 0.1)
y_true = f(x_test)
# plt.scatter(x_train, y_train)
# plt.show()

def plot_kernel_reg(y_hat):
    dltools.plot(x_test, [y_true, y_hat], "x", "y", legend = ["true", "pred"],
             xlim=[0, 5], ylim=[-1, 5])
    dltools.plt.plot(x_train, y_train, "o", alpha = 0.5)
    dltools.plt.show()

y_hat = torch.repeat_interleave(y_train.mean(), n_train)
plot_kernel_reg(y_hat)

X_repeat = x_test.repeat_interleave(n_train).reshape(-1, 50);
attention_weights = nn.functional.softmax(-((X_repeat - x_train) ** 2)/2, dim=1)
print(X_repeat)
print(x_train)
print(X_repeat - x_train)
print(f"attention_weights.shape:{attention_weights.shape}")
print(f"y_train.shape:{y_train.shape}")
# 本质是每个x_test对应的Y_hat值是由所有x_train对应的y_true值乘以（x_train和x_test的距离计算一个权重）
y_hat = torch.matmul(attention_weights, y_train)
print(f"y_hat.shape:{y_hat.shape}")
# plot_kernel_reg(y_hat)

# dltools.show_heatmaps(attention_weights.unsqueeze(0).unsqueeze(0),
#                      xlabel="Sorted training inputs",
#                      ylabel="Sorted training inputs"
#                      )
#dltools.plt.show()

# 定义模型
class NWKernelRegression(nn.Module):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.w = nn.Parameter(torch.rand((1,), requires_grad=True))

    def forward(self, queries, keys, values):
        # 规定一下queries的形状：（查询个数，键值对的个数）
        queries = queries.repeat_interleave(keys.shape[1]).reshape((-1, keys.shape[1]))
        self.attention_weights = nn.functional.softmax(-((queries - keys) * self.w) ** 2 / 2, dim=1)
        # bmm 批量矩阵乘法 第一个维度不变，后面两个维度进行矩阵乘法
        return torch.bmm(self.attention_weights.unsqueeze(1), values.unsqueeze(-1)).reshape(-1)

# 开始训练

X_tile = x_train.repeat((n_train, 1))
Y_tile = x_train.repeat((n_train, 1))

keys = X_tile[(1 - torch.eye(n_train)).type(torch.bool)].reshape((n_train, -1))
values = Y_tile[(1 - torch.eye(n_train)).type(torch.bool)].reshape((n_train, -1))
net = NWKernelRegression()
loss = nn.MSELoss(reduction="none")
trainer = torch.optim.SGD(net.parameters(), lr=0.5)
animator = dltools.Animator(xlabel="epoch", ylabel="loss", xlim=[1, 5])

for epoch in range(5):
    trainer.zero_grad()
    l = loss(net(x_train, keys, values), y_train)
    l.sum().backward()
    trainer.step()
    print(f"epoch:{epoch + 1}, loss:{float(l.sum()):.6f}")
    animator.add(epoch + 1, float(l.sum()))

print(f"net.w: {net.w}")

keys = x_train.repeat((n_train, 1))
values = y_train.repeat((n_train, 1))
y_hat = net(x_test, keys, values).unsqueeze(1).detach()
plot_kernel_reg(y_hat)

dltools.show_heatmaps(net.attention_weights.unsqueeze(0).unsqueeze(0),
                      xlabel="Sorted training inputs",
                      ylabel="Sorted training inputs"
                      )
dltools.plt.show()